<template>
    <a :class="className? className: 'ui button'" @click="showDialog">
        <slot></slot>
        <div class="ui modal" ref="dialog">
            <i class="close icon"></i>
            <div class="header">{{title ? title: 'json modal'}}</div>
            <div class="content">
                <json-editor v-model="value"/>
            </div>
            <div class="actions">
                <div class="ui black deny button">{{cancelText ? submitText : '取消'}}</div>
                <div class="ui positive button">{{submitText? submitText: '确定'}}</div>
            </div>
        </div>
    </a>
</template>

<script>
export default {
    name: 'json-modal',
    props: ['title', 'submitText', 'cancelText', 'initialValue', 'className'],
    data() {
        return {
            value: this.initialValue,
        }
    },
    methods: {
        showDialog() {
            $(this.$refs.dialog).modal({
                closable: false,
                onDeny: ()=>{
                    this.$emit('cancel')
                },
                onApprove: ()=>{
                    let jsonData = {}
                    if (this.value) {
                        try {
                            jsonData = JSON.parse(this.value)
                        } catch (e) {
                            return false
                        }
                    }
                    this.$emit('submit', {'data': jsonData})
                },
            }).modal('show')
        },
    },
}
</script>

